package middleware

import (
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/golang-jwt/jwt/v4"
	"shenmawl/utility"
)

//type Response struct {
//	Code    int         `json:"code" dc:"状态码"`
//	Message string      `json:"message" dc:"消息提示"`
//	Data    interface{} `json:"data"    dc:"执行结果"`
//}

func Auth(r *ghttp.Request) {
	var (
		jwtKey      = utility.JwtKey
		tokenString = r.Cookie.Get("jwt").String()
	)
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return jwtKey, nil
	})
	if err != nil || !token.Valid {
		r.Response.WriteJson(g.Map{
			"code":    202,
			"message": "用户未登录",
		})
		r.Exit()
	}

	r.Middleware.Next()
}

func ResponseWriteJson(r *ghttp.Request) {
	r.Middleware.Next()
	var (
		msg             string
		res             = r.GetHandlerResponse()
		err             = r.GetError()
		responseContent = r.Response.BufferString()
		//dataRes map[string]interface{}
	)
	jsonData, err := gjson.DecodeToJson(responseContent)

	if err != nil {
		msg = err.Error()
	} else {
		msg = jsonData.Get("message").String()
	}
	// 获取响应内容
	//responseContent := r.Response.BufferString()
	//g.Log().Infof(r.Context(), responseContent)
	// 解析JSON响应数据
	//if jsonData, err := gjson.DecodeToJson(responseContent); err == nil {
	//	// 获取特定参数，例如用户名
	//	if message := jsonData.Get("message").String(); message != "" {
	//		g.Log().Infof(r.Context(), "message: %s", message)
	//	}
	//}
	//清空原始数据并写入自定义格式
	r.Response.ClearBuffer()
	r.Response.WriteJson(Response{
		Code:    jsonData.Get("code").Int(),
		Message: msg,
		Data:    res,
	})
}

// MiddlewareCORS 处理跨域请求
func MiddlewareCORS(r *ghttp.Request) {
	r.Response.CORSDefault()
	r.Middleware.Next()
}
